package cn.emall.sso.service.impl;

import cn.emall.mapper.TbUserMapper;
import cn.emall.pojo.TbUser;
import cn.emall.pojo.TbUserExample;
import cn.emall.sso.service.RegisterService;
import cn.emall.utils.EmallResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class RegisterServiceImpl implements RegisterService{

    @Autowired
    private TbUserMapper tbUserMapper;


    @Override
    public EmallResult checkData(String param, int type) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        //根据不同的type生成不同的查询条件
        //1：用户名 2：手机号 3：邮箱
        if(type == 1){
            criteria.andUsernameEqualTo(param);
        }else if(type == 2){
            criteria.andPhoneEqualTo(param);
        }else if(type == 3){
            criteria.andEmailEqualTo(param);
        }else {
            return EmallResult.build(400,"数据类型错误");
        }
        //执行查询
        List<TbUser> userList = tbUserMapper.selectByExample(example);
        //判断结果中是否包含数据
        if (userList != null && userList.size() > 0){
            //如果有数据返回false
            return EmallResult.ok(false);
        }else{
            //如果没有数据返回true
            return EmallResult.ok(true);
        }
    }

    @Override
    public EmallResult register(TbUser tbUser) {
        //数据有效性校验
        if(StringUtils.isBlank(tbUser.getUsername()) || StringUtils.isBlank(tbUser.getPassword()) ||
                StringUtils.isBlank(tbUser.getPhone())) {
            return EmallResult.build(400, "用户数据不完整，注册失败");
        }
        //1：用户名 2：手机号 3：邮箱
        EmallResult result = checkData(tbUser.getUsername(),1);
        if (!(boolean)result.getData()){
            return EmallResult.build(400, "此用户名已经被占用");
        }
        result = checkData(tbUser.getPhone(),2);
        if (!(boolean)result.getData()){
            return EmallResult.build(400, "此电话号码已经被占用");
        }
        //补全pojo的属性
        tbUser.setCreated(new Date());
        tbUser.setUpdated(new Date());
        //对密码进行md5加密
        String md5Pass = DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes());
        tbUser.setPassword(md5Pass);
        //把用户数据插入到数据库中
        tbUserMapper.insert(tbUser);
        //返回添加成功
        return EmallResult.ok();
    }
}
